<template>
  <div class="administer">
    <div class="administerNav">
      <backHeader></backHeader>
    </div>
    <div class="administerCont">
      <div class="user html_pst">
        <div class="searchBoxs">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="登录名">
              <el-input v-model="request.loginNameLike"></el-input>
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="request.userNameLike"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search(1)">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="roleControl">
          <ul style="text-align:right">
                <li v-show="totalCount<maxUserNum" @click="showAddForm()"><i class="el-icon-circle-plus-outline"></i>添加</li>
                <li @click="showEditView()" ><i class="el-icon-edit-outline"></i>修改</li>
                <li @click="deleteUser()"><i class="el-icon-delete"></i>删除</li>
                <li @click="ShowResetPassword()"><i class="el-icon-edit-outline"></i>重置密码</li>
                <li @click="userRole()"><i class="el-icon-s-fold"></i>用户角色</li>
          </ul>
          <el-table :data="tableData" border style="width: 100%" :max-height="tableHeight" :highlight-current-row="true" @current-change="tableDataChoose">
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="loginName" label="登录名"></el-table-column>
            <el-table-column prop="userName" label="昵称"></el-table-column>
            <el-table-column prop="userBirthday" label=" 出生日期 " width="105">
              <template slot-scope="scope">{{getDate(scope.row.userBirthday)}}</template>
            </el-table-column>
            <el-table-column prop="userGender" label=" 性别">
              <template slot-scope="scope">{{scope.row.userGender == 1 ? "男" : "女"}}</template>
            </el-table-column>
            <el-table-column prop="userEmail" width="150" label=" 邮箱"></el-table-column>
            <el-table-column prop="userPhone" label=" 手机号"></el-table-column>
            <el-table-column prop="createDate" label=" 创建时间"></el-table-column>
            <el-table-column prop="userState" label=" 状态">
              <template slot-scope="scope">{{scope.row.userState == 1 ? "有效" : "无效"}}</template>
            </el-table-column>
            <!-- <el-table-column prop="loginCount" label=" 登录次数"></el-table-column> -->
            <el-table-column prop="preLoginTime" width="150" label=" 上次登录时间"></el-table-column>
            <!-- <el-table-column prop="userDesc" label=" 描述"></el-table-column> -->
            <!-- <el-table-column width="100" label="操作"  fixed="right">
              <template slot-scope="scope">
                <div class="managementProductList_btn">
                  <el-button @click="showEditView(scope.row)" type="text" size="small">修改</el-button>
                  <el-button @click="ShowResetPassword(scope.row)" type="text" size="small">重置密码</el-button>
                  <el-button
                    @click="deleteUser(scope.row.id)"
                    type="text"
                    size="small"
                    class="remove"
                  >删除</el-button>
                </div>
              </template>
            </el-table-column> -->
          </el-table>
          <div style="padding:10px;text-align:center">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="request.page"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="request.rows"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 添加/修改 -->
    <el-dialog 
    :title="modelTitle" 
    :visible.sync="isShowModel"
     custom-class="userRole pop-up" 
     v-dialogDrag
     >
      <el-form ref="form" :inline="true" label-width="80px">
        <el-form-item label="登录名" :rules="[{ required: true, trigger: 'blur' }]">
          <el-input style="width:260px" v-model="form.loginName" :readonly="modelTitle!='添加用户'" ></el-input>
        </el-form-item>
        <el-form-item label="昵称" :rules="[{ required: true, trigger: 'blur' }]">
          <el-input style="width:260px" v-model="form.userName"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select style="width:260px" v-model="form.userGender">
            <el-option v-for="item in SexOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电子邮箱" :rules="[{ required: true, trigger: 'blur' }]">
          <el-input style="width:260px" v-model="form.userEmail"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input style="width:260px" v-model="form.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker style="width:260px" v-model="form.userBirthday" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="描述" class="maoshu">
          <el-input style="width:260px" type="textarea" v-model="form.userDesc"></el-input>
        </el-form-item>
        <el-form-item class="botm">
          <el-button @click="isShowModel=false">取消</el-button>
          <el-button v-if="modelTitle=='添加用户'" @click="addUser()" type="primary">确定</el-button>
          <el-button v-else @click="editUser()" type="primary">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 重置密码 -->
    <el-dialog title="重置密码" :visible.sync="isShowPass" width="30%" custom-class=" pop-up" v-dialogDrag>
      <el-form ref="form" label-width="80px">
        <el-form-item label="新密码">
          <el-input type="password" v-model="repassForm.password" placeholder="8-16位密码，区分大小写"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="repassForm.qrPassword" placeholder="8-16位密码，区分大小写"></el-input>
        </el-form-item>
        <el-form-item class="botm">
          <el-button @click="isShowPass =false">取消</el-button>
          <el-button @click="resetPass()" type="primary">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 用户角色 -->
     <el-dialog title="用户角色管理" :visible.sync="userRoledialog" width="50%" custom-class=" pop-up" v-dialogDrag>
       <el-table ref="userROleTable" :data="allRoleList" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column  type="selection" width="55"> </el-table-column>
        <el-table-column  prop="roleChName" label="角色名称" > </el-table-column>
        <el-table-column  prop="roleDesc" label="描述" > </el-table-column>
      </el-table>
      
            <el-pagination
              @current-change="handleCurrentChangeRole"
              :current-page="CurrentPageRole"
              :page-size="10"
              layout="total, prev,pager, next"
              :total="totalCountRole"
            ></el-pagination>
        <div style="margin-top: 20px;text-align: center;">
        <el-button @click="userRoledialog = false">取消</el-button>
        <el-button @click="saveRole" type="primary">确定</el-button>       
      </div>
    </el-dialog>
  </div>
</template>
<script>
import backHeader from "@/views/common/backHeader.vue";
export default {
  data() {
    return {
      tableHeight:200,
      SexOptions:[
        {
          label:'男',
          value:1
        },
        {
          label:'女',
          value:2
        }
      ],
      form: {
        loginName: "",
        userBirthday: "",
        userDesc: "",
        userEmail: "",
        userGender: "",
        userName: "",
        userPhone: ""
      },
      maxUserNum:0,
      tableUserRole:[
        {name:'名字',name1:'描述'}
      ],
      modelTitle: "添加用户",
      isShowModel: false,
      userRoledialog:false,
      request: {
        userType:1,
        page: 1,
        rows: 20,
        loginNameLike: "",
        userNameLike: ""
      },
      tableData: [],
      totalCount: 0,
      isShowPass: false,
      repassForm: {
        id: 0,
        password: "",
        qrPassword:'',
      },
      currentChooseDataRow:{},
      allRoleList:[],
      currentUserRole:[],
      currentUserId:'',
      multipleSelection:[],
      totalCountRole:0,
      CurrentPageRole:1,
    };
  },
  watch:{
    userRoledialog(n,o){
          this.$nextTick(()=>{
            this.refreshUserRoleList()
          })
    },
    CurrentPageRole(n,o){
        this.$nextTick(()=>{
            this.refreshUserRoleList()
          })
    }
  },
  methods: {
    refreshUserRoleList(){
      this.allRoleList.forEach(row => {
                this.$refs.userROleTable.toggleRowSelection(row,false);
                for(var i = 0;i<this.currentUserRole.length;i++){
                  if(this.currentUserRole[i].id == row.id){
                    this.$refs.userROleTable.toggleRowSelection(row,true);
                  }
                }
            })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    userRole(){
      if(this.currentChooseDataRow.id == null){
        this.$message.error("请先选择数据！")
        return false
      }
      let self = this
      this.$http.get('/api/users/'+this.currentChooseDataRow.id,{},function(res){
        if(res.success){
          self.currentUserRole = res.data.roles
          self.userRoledialog = true
          console.log(res)
        }
      })
    },
    saveRole(){
      //  if(this.multipleSelection.length == 0){
      //           this.$message.error('请选择权限！')
      //           return false
      //       }
            var ids = []
            for(var i = 0;i<this.multipleSelection.length;i++){
                ids.push(this.multipleSelection[i].id)
            }
            let self = this
      this.$http.postObj('/api/users/roles/'+this.currentChooseDataRow.id,ids,function(res){
        console.log(res)
        if(res.success){
                self.userRoledialog = false
                self.$message({
                    message: "修改成功！",
                    type: "success"
                })
            }else{
              self.$message.error(res.data)
            }
      })

    },
    tableDataChoose(row){
      this.currentChooseDataRow = row
      console.log(this.currentChooseDataRow)
    },
    getDate(date){
      if(date != null && date != ''){
        return date.split(' ')[0]
      }
      return ""
    },
    initData() {

      let self = this
      this.$http.get("/api/users/getCurrentUser", {}, function(res) {
        if (res.success) {
          self.maxUserNum = res.data.organization.maxUserNum
        }
      });

      this.search(1);
      this.searchUserRole(1);
    },
    search(page) {
      this.request.page = page
      let self = this;
      this.$http.postObj("/api/pageJson", this.request, function(res) {
        if (res.success) {
          self.tableData = res.data.rows;
          self.totalCount = res.data.total;
        }
      });

      
    },
    searchUserRole(page){
      this.CurrentPageRole = page
      let self = this
      this.$http.postObj('/api/roles/pageJson',{page:this.CurrentPageRole,rows:10},function(res){
        if(res.success){
          self.allRoleList = res.data.rows
          self.totalCountRole = res.data.total
        }
      })
    },
    handleCurrentChange(page) {
      this.search(page);
    },
    handleSizeChange(pageSize) {
      this.request.rows = pageSize;
      this.search(1);
    },
    handleCurrentChangeRole(page){
      this.searchUserRole(page);
    },
    showAddForm() {
      this.isShowModel = true;
      this.modelTitle = "添加用户";
      this.form = {
        loginName: "",
        userBirthday: "",
        userDesc: "",
        userEmail: "",
        userGender: "",
        userName: "",
        userPhone: ""
      };
    },
    addUser() {
      if(this.form.loginName == ''){
        this.$message.error('请输入登录名！')
        return false
      }
      if(this.form.userName == ''){
        this.$message.error('请输入昵称！')
        return false
      }
          var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
                if (this.form.userEmail == '') {
                    this.$message({
                        message: '请输入邮箱！',
                        type: 'error'
                    })
                    return
                }
                if(!regEmail.test(this.form.userEmail)){
                    this.$message({
                        message: '邮箱格式不正确！',
                        type: 'error'
                    })
                    return
                }
      let self = this;
      this.$http.postObj("/api/users", this.form, function(res) {
        self.search(1);
        self.isShowModel = false;
        if (res.success) {
          self.$message({
            message: "添加成功！",
            type: "success"
          });
        }else{
              self.$message.error(res.data)
            }
      });
    },
    showEditView() {
      if(this.currentChooseDataRow.id == null){
        this.$message.error("请先选择数据！")
        return false
      }
      this.isShowModel = true;
      this.modelTitle = "修改用户";
      var row = this.currentChooseDataRow
      this.form = {
        loginName: row.loginName,
        userBirthday: row.userBirthday,
        userDesc: row.userDesc,
        userEmail: row.userEmail,
        userGender: row.userGender,
        userName: row.userName,
        userPhone: row.userPhone,
        id: row.id
      };
    },
    editUser() {
      if(this.form.loginName == ''){
        this.$message.error('请输入登录名！')
        return false
      }
      if(this.form.userName == ''){
        this.$message.error('请输入昵称！')
        return false
      }
        var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
                if (this.form.userEmail == '') {
                    this.$message({
                        message: '请输入邮箱！',
                        type: 'error'
                    })
                    return
                }
                if(!regEmail.test(this.form.userEmail)){
                    this.$message({
                        message: '邮箱格式不正确！',
                        type: 'error'
                    })
                    return
                }
      let self = this;
      this.$http.putObj("/api/users", this.form, function(res) {
        self.search(1);
        self.isShowModel = false;
        if (res.success) {
          self.$message({
            message: "修改成功！",
            type: "success"
          });
        }else{
              self.$message.error(res.data)
            }
      });
    },
    deleteUser() {
      if(this.currentChooseDataRow.id == null){
        this.$message.error("请先选择数据！")
        return false
      }
      var id = this.currentChooseDataRow.id
      let self = this;
      this.$confirm('您确定要删除吗?','提示',{
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
      }).then(()=>{
        this.$http.deletePath("/api/users/" + id, {}, function(res) {
          if (res.success) {
            self.$message({
              message: "删除成功！",
              type: "success"
            });
          }else{
              self.$message.error(res.data)
            }
          self.search(1);
        });
    }).catch(()=>{});
    },
    ShowResetPassword() {
      this.repassForm.password = ''
      this.repassForm.qrPassword = ''
      if(this.currentChooseDataRow.id == null){
        this.$message.error("请先选择数据！")
        return false
      }
      var row = this.currentChooseDataRow
      this.isShowPass = true;
      this.repassForm.id = row.id;
    },
    resetPass() {
      if (this.repassForm.password == "") {
        this.$message.error("请输入新密码");
        return false;
      }
      if (this.repassForm.qrPassword == "") {
        this.$message.error("请输入确认密码");
        return false;
      }

          if(this.repassForm.password.length < 8 || this.repassForm.password.length > 16){
              this.$message.error("新密码必须长度为8-16位")
              return
          }
          if(this.repassForm.qrPassword.length < 8 || this.repassForm.qrPassword.length > 16){
              this.$message.error("确认密码必须长度为8-16位")
              return
          }
      if (this.repassForm.password != this.repassForm.qrPassword) {
        this.$message.error("两次密码不一致");
        return false;
      }
      let self = this;
      this.$http.postQuery(
        "/api/resetPwd/" + this.repassForm.id,
        {password:this.repassForm.password},
        function(res) {
          console.log(res);
          self.search(1);
          if (res.success) {
            self.$message({
              message: "修改成功！",
              type: "success"
            });
          }else{
              self.$message.error(res.data)
            }
          self.isShowPass = false
        }
      );
    }
  },
  created() {
    this.initData();
  },
  components: {
    backHeader
  },
  mounted(){
        this.$nextTick(function () {
            this.tableHeight = window.innerHeight - 280;
            
            // 监听窗口大小变化
            let self = this;
            window.onresize = function() {
                self.tableHeight = window.innerHeight - 280
            }
        })
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.userRole.pop-up .el-date-editor.el-input, .el-date-editor.el-input__inner{
  width: 100%;
}
.managementProductList_btn{
  .el-button--text{
    padding: 0px 15px;
    margin-left: 0 !important;
  }
}
.user {
  .el-form {
    width: 100%;
    .el-form-item:nth-child(2) {
      margin-left: 20px;
    }
    .el-button--primary {
      background-color: #5b65a1;
      border-radius: 4px;
      border: none;
    }
  }
}
</style>
<style rel="stylesheet/scss" lang="scss">
.roleControl_ul{
  margin: 10px 0;
  li{
    button{
      padding: 12px 20px;
      font-size: 14px;
      background-color: #5b65a1;
      border-radius: 4px;
      border: none;
      color: #fff;
    }
    &:hover{
      button{
        background-color: #5b65a1;
        color: #fff;
      }
    }
  }
}
.el-dialog__wrapper .el-dialog.userRole{
height: auto;
  max-height: 80vh;
  overflow: auto;
}
.userRole {
  width:800px;
  .el-form {
    overflow: hidden;
    .el-form-item {
      width: 50%;
      float: left;
      margin-right: 0;
      .el-form-item__content {
        width: calc(100% - 90px);
        width: -webkit-calc(100% - 90px);
      }
      &.maoshu {
        width: 100%;
      }
      &.botm {
        width: 100%;
      }
    }
  }
}
.pop-up {
  .el-menu-item,
  .el-submenu__title {
    height: 36px;
    line-height: 36px;
  }
  .el-menu-item-group__title {
    display: none;
  }
  .el-submenu .el-menu-item {
    padding-left: 60px !important;
  }
  .el-menu {
    border: none;
  }
  .el-dialog__header {
    text-align: center;
    .el-dialog__title {
      font-weight: bold;
    }
    .el-dialog__headerbtn {
      width: 22px;
      height: 22px;
      text-align: center;
      line-height: 24px;
      border-radius: 50%;
      background-color: #5962a3;
      i {
        color: #fff;
      }
    }
  }
  .el-dialog__body {
    padding-top: 10px;
    .el-button--primary {
      background-color: #5962a3;
      border-radius: 3px;
      border: none;
    }
  }
  .botm {
    .el-form-item__content {
      margin-left: 0 !important;
    }
    text-align: center;
  }
  .el-select {
    width: 100%;
  }
  .el-dialog__footer {
    text-align: center;
    .el-button--primary {
      background-color: #5962a3;
      border-radius: 3px;
      border: none;
    }
  }
  .srte {
    width: 100%;
    display: inline-block;
    .lt {
      width: 48%;
      float: left;
      margin-right: 4%;
      .add {
        color: #333;
        font-size: 14px;
        margin-bottom: 10px;
      }
    }
    .rt {
      width: 48%;
      float: left;
      .remor {
        color: #333;
        font-size: 14px;
        margin-bottom: 10px;
      }
    }
    .title {
      border: 1px solid #ebeef5;
      border-bottom: 0;
      padding: 6px;
    }
    td,
    th {
      text-align: center;
      font-size: 12px;
      padding: 5px 0;
    }
  }
}
</style>
